//
//  HeaderCell.swift
//  JKTools
//
//  Created by 姜奎 on 2/19/25.
//
import Cocoa

class SessionListHeaderCell: NSTableCellView {

    static let reuseIdentifier = NSUserInterfaceItemIdentifier("SessionListHeaderCell")

    private let titleLabel: NSTextField = {
        let label = NSTextField(labelWithString: "")
        label.font = .systemFont(ofSize: 13, weight: .semibold)
        label.textColor = .secondaryLabelColor
        label.lineBreakMode = .byTruncatingTail
        return label
    }()

    private let separator: NSBox = {
        let box = NSBox()
        box.boxType = .separator
        return box
    }()

    override init(frame frameRect: NSRect) {
        super.init(frame: frameRect)
        setupUI()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupUI() {
        addSubview(titleLabel)
        addSubview(separator)

            // 自动布局约束
        titleLabel.translatesAutoresizingMaskIntoConstraints = false
        separator.translatesAutoresizingMaskIntoConstraints = false

        NSLayoutConstraint.activate([
            titleLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 16),
            titleLabel.centerYAnchor.constraint(equalTo: centerYAnchor),
            titleLabel.trailingAnchor.constraint(lessThanOrEqualTo: trailingAnchor, constant: -16),

            separator.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 12),
            separator.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -12),
            separator.bottomAnchor.constraint(equalTo: bottomAnchor),
            separator.heightAnchor.constraint(equalToConstant: 1)
        ])
    }

    func configure(with title: String) {
        titleLabel.stringValue = title
    }

    override func prepareForReuse() {
        super.prepareForReuse()
        titleLabel.stringValue = ""
    }

}

extension SessionListHeaderCell: CellProtocol {

    static func createOrUpdate<T, D, V>(_ contentView: T, with data: D) -> V? {

        guard let contentView = contentView as? NSOutlineView, let data = data as? String else { return nil }

        if let cell = contentView.makeView(withIdentifier: SessionListHeaderCell.reuseIdentifier, owner: nil) as? SessionListHeaderCell {

            cell.configure(with: data)

            return cell as? V

        }

            // 创建新实例

        let newCell = SessionListHeaderCell()

        newCell.identifier = SessionListHeaderCell.reuseIdentifier // 关键：设置复用标识符

        newCell.configure(with: data)

        return newCell as? V
    }
}

